from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework import status
from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample
from drf_spectacular.types import OpenApiTypes
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.contrib.auth import get_user_model
from user_app.models import User
from vehicle_app.models import Vehicle
from order_app.models import Order
from auth_app.models import SmsVerification

UserModel = get_user_model()

class HealthCheckView(APIView):
    """健康检查视图"""
    
    permission_classes = [AllowAny]
    
    @extend_schema(
        description="健康检查接口",
        responses={
            200: {
                "type": "object",
                "properties": {
                    "status": {"type": "string", "description": "服务状态"},
                    "version": {"type": "string", "description": "API版本"}
                }
            }
        }
    )
    def get(self, request):
        """健康检查"""
        return Response({
            'status': 'ok',
            'version': 'v1.0.0'
        })


@method_decorator(login_required, name='dispatch')
class DashboardView(APIView):
    """仪表盘视图"""
    
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        """渲染仪表盘页面"""
        return render(request, 'dashboard/index.html')


class DashboardStatsView(APIView):
    """仪表盘统计数据API"""
    
    permission_classes = [IsAuthenticated]
    
    @extend_schema(
        description="获取仪表盘统计数据",
        responses={
            200: {
                "type": "object",
                "properties": {
                    "total_users": {"type": "integer", "description": "总用户数"},
                    "total_vehicles": {"type": "integer", "description": "总车辆数"},
                    "total_orders": {"type": "integer", "description": "总订单数"},
                    "pending_reviews": {"type": "integer", "description": "待审核数量"}
                }
            }
        }
    )
    def get(self, request):
        """获取统计数据"""
        total_users = User.objects.count()
        total_vehicles = Vehicle.objects.count()
        total_orders = Order.objects.count()
        
        # 返回统计数据
        return Response({
            'total_users': total_users,
            'total_vehicles': total_vehicles,
            'total_orders': total_orders,
            'pending_reviews': 0  # 占位符，后续可以实现
        })


@method_decorator(login_required, name='dispatch')
class ProfileView(APIView):
    """个人中心视图"""
    
    permission_classes = [IsAuthenticated]
    
    def get(self, request):
        """渲染个人中心页面"""
        return render(request, 'profile/index.html')


class ChangePasswordView(APIView):
    """修改密码视图"""
    
    permission_classes = [IsAuthenticated]
    
    @extend_schema(
        description="修改用户密码",
        request={
            "type": "object",
            "properties": {
                "old_password": {"type": "string", "description": "旧密码"},
                "new_password": {"type": "string", "description": "新密码"},
                "confirm_password": {"type": "string", "description": "确认新密码"}
            },
            "required": ["old_password", "new_password", "confirm_password"]
        },
        responses={
            200: {
                "type": "object",
                "properties": {
                    "message": {"type": "string", "description": "成功消息"}
                }
            },
            400: {
                "type": "object",
                "properties": {
                    "error": {"type": "string", "description": "错误信息"}
                }
            }
        }
    )
    def post(self, request):
        """修改密码"""
        user = request.user
        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')
        confirm_password = request.data.get('confirm_password')
        
        # 检查旧密码是否正确
        if not user.check_password(old_password):
            return Response(
                {'error': '旧密码不正确'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 检查新密码和确认密码是否一致
        if new_password != confirm_password:
            return Response(
                {'error': '新密码和确认密码不一致'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 检查密码长度
        if len(new_password) < 6:
            return Response(
                {'error': '密码长度至少6位'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 修改密码
        user.set_password(new_password)
        user.save()
        
        return Response({'message': '密码修改成功'})